package JAVA300.第十二章网络编程;

import java.io.*;
import java.net.Socket;

/**
 * tcp
 * 模拟登录--多个客户端输入登录信息
 * 传送用户名和密码
 *---内容和单一的没区别 学会封装函数
 *
 * 主要添加获取用户输入
 */

public class web05_TCP5_MultiLoginClient {
    public static void main(String[] args) throws IOException {
        System.out.println("--------client-----------");
        //**********************准备数据

        //1。建立连接，使用socket创建客户端+服务器的地址和端口
        Socket socket = new Socket("localHost",8888);

        //2.操作:输入输出流--建议使用data流，不用操作字节
        //先请求后响应 所以不需要线程
        //将参数写到init获取返回值 不用传参了
        new Send(socket).send();
        //获取服务器登录判断的返回
        System.out.println(new Receive(socket).read());

        //3。释放资源
        socket.close();

    }

    static class Send{
        private DataOutputStream dos;
        private BufferedReader console;
        private String msg;//返回的信息

        public Send(Socket socket ) {

            try {
                this.dos =  new DataOutputStream(socket.getOutputStream());
                console= new BufferedReader(new InputStreamReader(System.in));
                this.msg =init();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void send(){
            //String msg="uname="+user+"&"+"upwd="+pwd;//也可以封装成对象
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        public String init(){
            try {
                System.out.println("input ur name :");
                String user = console.readLine();//用到console 所以构造函数里初始化要在调用之前
                System.out.println("input ur pwd:");
                String pwd = console.readLine();
                return "uname="+user+"&"+"upwd="+pwd;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "";


        }
    }

    static class Receive{
        private DataInputStream dis;

        public Receive(Socket socket) {
            try {
                this.dis = new DataInputStream(socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String read(){
            String loginMsg = "";
            try {
                loginMsg = dis.readUTF();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return loginMsg;

        }
    }

    public void release(){

    }
}
